/**
 * 
 */
package edu.gtcfla.km.appmodules.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.multipart.MultipartFile;

import edu.gtcfla.km.appmodules.service.UploadFileManager;
import edu.gtcfla.km.appmodules.vo.UploadFileFormVO;

/**
 * @author vison
 *
 */
public class SimpleUploadFileManager implements UploadFileManager, InitializingBean {
	
	private static final Logger logger = LoggerFactory.getLogger( SimpleUploadFileManager.class );
	
	
	private String saveServerPath;
	
	

	public String getSaveServerPath() {
		return saveServerPath;
	}



	public void setSaveServerPath(String saveServerPath) {
		this.saveServerPath = saveServerPath;
	}



	/* (non-Javadoc)
	 * @see edu.gtcfla.km.appmodules.service.UploadFileManager#saveOne(org.springframework.web.multipart.MultipartFile)
	 */
	@Override
	public UploadFileFormVO saveOne(MultipartFile file) {
		// TODO Auto-generated method stub
		String orginalFile = file.getOriginalFilename();
		String fieldName  = file.getName();
		String contentType = file.getContentType();
		

				
		
		int startExtFileInd =  orginalFile.lastIndexOf(".");
		String extFile = "";
		if (startExtFileInd != -1) {
			extFile = orginalFile.substring( startExtFileInd, orginalFile.length());
		} else {
			startExtFileInd = fieldName.lastIndexOf(".");
			extFile = orginalFile.substring( startExtFileInd, orginalFile.length());
		}
		
		
		if (logger.isDebugEnabled() ) {
			logger.debug("upload file : " + extFile + " , " + orginalFile + " , " + contentType );
		}
		
		UploadFileFormVO uff = null;
		
		try {
			// ---- create basic file ---
			File dest = File.createTempFile("upload-", extFile, uploadPath); 
			file.transferTo(dest);
			
			uff = new UploadFileFormVO();
			uff.setContentType( contentType );
			uff.setExt( extFile.substring(1) );
			uff.setFileName(dest.getName());
			uff.setTitle( orginalFile );
	
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return uff;

	}

	
	

	@Override
	public File getRealPath(String inputFile) {
		// TODO Auto-generated method stub
		File outfile = new File(this.uploadPath , inputFile);
		return outfile;
	}




	private File uploadPath;

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		uploadPath = new File(saveServerPath);
		if (!uploadPath.exists()) {
			uploadPath.mkdirs();
		}

	}

	
	
}
